<template>
  <div class="pages">
    <!-- 头部导航 -->
    <div class="header">
      <button class="back-button fff" @click="router.back()">
        <span class="back-icon">←</span>
      </button>
      <span class="header-title fff">选择声音模型</span>
    </div>

    <div class="choose-page">
      <div class="choose-tips">
        <div class="left">小贴士</div>
        <div class="right">平台支持五种主流语种，内置20种风格多样的声音模型，任选喜欢的语音风格进行体验</div>
      </div>

      <div class="choose-title">选择声音模型</div>
      <div style="height: 19px;"></div>

      <div v-if="!store.runningData">
          请先开启云算力
      </div>
      <div v-else class="choose-sound-list">
        <div
          class="item"
          v-for="(item, index) in store.filesMuc"
          :key="item.path || index"
          :class="{ active: isActive(item) }"
          @click="play(item)"
        >
          <div class="text">
            {{ index + 1 }}. {{ item.name || item.path }}
          </div>
          <div v-if="isActive(item)" class="playing-badge">已选择</div>
        </div>
      </div>

      <div style="height: 75px;"></div>
      <div class="btn-block">
        <button class="live-btn" @click="router.back(); store.configTabId = 2">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from '@/stores/data'

const store = useStore()
const router = useRouter()

// ---- 持久化已选 ----
const LS_KEY = 'okmax_selected_voice_path'
const activePath = ref<string | null>(null)

// ---- 单例播放器 ----
const player = new Audio()
player.preload = 'none'

// 生成完整可播放 URL： http://<ip>:1352/<path>

const fullUrl = (p?: string) => {
  return "https://api.nextai.club/api" + "/openAudio?name=" + p + "&ip=" + store.runningData?.ip;
}

const isActive = (item: any) => item?.path === activePath.value

// 点击播放并记录
const play = async (item: any) => {
  localStorage.setItem("muc", item?.path)
  activePath.value = item?.name || null
  const url = fullUrl(item?.name)
  console.log(url)
  if (!url) return
  try {
    // 切换音源前先停掉
    try { player.pause() } catch {}
    player.src = url
    await player.play()
    
    // 仅把 path 持久化（按你的要求）
    
  } catch (err) {
    console.error('播放失败：', err)
  }
}

onMounted(async () => {
  if(store.runningData) {
     // 拉取文件列表
    await store.listFiles(store.runningData?.ip)

    // 恢复上次选择（如果该 path 仍存在）
    const saved = localStorage.getItem("muc")
    if (saved) {
      const exist = (store.filesMuc || []).some((f: any) => f.path === saved)
      if (exist) activePath.value = saved
    }
  }
})

onUnmounted(() => {
  try { player.pause() } catch {}
  player.src = ''
})

</script>

<style lang="scss" scoped>
.pages {
  box-sizing: border-box;
  background: #006CFF;
  overflow: hidden;
}

/* 顶部 header（若在别处已定义，可删） */
.header {
  display: flex; align-items: center; gap: 8px;
  padding: 12px 16px;
}
.header-title { font-weight: 600; }

.choose-page {
  padding: 22px 16px;
  box-sizing: border-box;
  width: 100%;
  border-radius: 20px 20px 0 0;
  background: #ffffff;
  flex: 1;
  overflow-y: auto;

  .choose-tips {
    display: flex;
    margin-bottom: 38px;
    .left {
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 10px;
      color: #006CFF;
      height: 20px;
      background: #E4F2FD;
      margin-right: 11px;
      border-radius: 4px;
      padding: 0 3px;
      box-sizing: border-box;
      line-height: 20px;
    }
    .right {
      flex: 1;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #595959;
      line-height: 20px;
    }
  }

  .choose-title {
    font-family: PingFang SC, PingFang SC;
    font-weight: 600;
    font-size: 20px;
    color: #1A1A1A;
  }

  .choose-sound-list {
    display: flex;
    flex-direction: column;
    gap: 10px;

    .item {
      position: relative;
      padding: 12px 14px;
      border-radius: 10px;
      border: 1px solid #E9E9E9;
      cursor: pointer;
      transition: all .15s ease;

      .text {
        font-size: 14px;
        color: #333;
        word-wrap: break-word;
        word-break: break-all;
        white-space: normal;
        line-height: 1.4;
      }

      &:hover {
        border-color: #B6D7FF;
        box-shadow: 0 2px 8px rgba(0, 108, 255, 0.08);
      }
    }

    .item.active {
      background: linear-gradient(90deg, #E9F3FF 0%, #F2F8FF 100%);
      border-color: #006CFF;
      .text { color: #006CFF; font-weight: 600; padding-right: 50px;}
    }

    .playing-badge {
      position: absolute;
      right: 10px;
      top: 10px;
      font-size: 12px;
      color: #006CFF;
      padding: 2px 8px;
      background: rgba(0,108,255,0.08);
      border-radius: 12px;
    }
  }
}

.btn-block {
  position: absolute;
  left: 0;
  bottom: 17px;
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 0 16px;
  box-sizing: border-box;
}
</style>
